import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import RegisterView from '@/views/register.vue'
import Login from '@/views/Login.vue'
import { useCounterStore } from '@/stores/counter'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    
    {
      path: '/home',
      name: 'home',
      component: HomeView,
      meta: { qiankun: true } // 需要乾坤
    },
    {
      path: '/register',
      name: 'register',
      component: RegisterView,
      meta: { qiankun: false } // 不需要乾坤
    },
    {
      path: '/login',
      name: 'login',
      component: Login,
      meta: { qiankun: false } // 不需要乾坤
    },
    {
      path: "/",
      component: () => import("@/views/home/home.vue"),
      redirect: 'work',
      children: [
        {
          path: "work",
          name: "work",
          component: () => import("@/views/home/work.vue"),
        },
        {
          path: "zu",
          name: "zu",
          component: () => import("@/views/home/zu.vue"),
        },
        {
          path: "yuan",
          name: "yuan",
          component: () => import("@/views/home/yuan.vue"),
        },
        {
          path: "kao",
          name: "kao",
          component: () => import("@/views/home/kao.vue"),
        },
        {
          path: "xin",
          name: "xin",
          component: () => import("@/views/home/xin.vue"),
        },
        {
          path: "zhao",
          name: "zhao",
          component: () => import("@/views/home/zhao.vue"),
        },
        {
          path: "ji",
          name: "ji",
          component: () => import("@/views/home/ji.vue"),
        },
        {
          path: "xi",
          name: "xi",
          component: () => import("@/views/home/xi.vue"),
        },
      ],
    },
    // 将子应用路由放在顶层，避免嵌套路由问题
    {
      path: '/staff/:page*',
      name: 'staff-app',
      component: () => import("@/views/home/home.vue"),
      meta: { roles: ['CEO', 'HR', 'ADMIN', '人事', '行政部'] }
    },
    {
      path: '/organization/:page*',
      name: 'organization',
      component: () => import("@/views/home/home.vue"),
      meta: { roles: ['CEO', 'HR', 'ADMIN', '人事', '行政部'] }
    },
    {
      path: '/react/:page*',
      name: 'react',
      component: () => import("@/views/home/home.vue"),
      meta: { roles: ['CEO', 'HR', '人事'] }
    },
    {
      path: '/administration/:page*',
      name: 'administration',
      component: () => import("@/views/home/home.vue"),
      meta: { roles: ['CEO', 'ADMIN', '行政部'] }
    },
    {
      path: '/finance/:page*',
      name: 'finance',
      component: () => import("@/views/home/home.vue"),
      meta: { roles: ['CEO', 'HR', '人事'] }
    },
    {
      path: '/process/:page*',
      name: 'process',
      component: () => import("@/views/home/home.vue"),
      meta: { roles: ['CEO', 'HR', 'EMPLOYEE', 'ADMIN', '员工', '人事', '行政部'] }
    },

  ],
})

// 添加全局导航守卫
router.beforeEach((to, from, next) => {
  console.log('[主应用] 路由变化:', from.path, '->', to.path);
  
  // 不需要登录验证的路由
  const publicRoutes = ['/login', '/register'];
  
  // 如果是公开路由，直接放行
  if (publicRoutes.includes(to.path)) {
    next();
    return;
  }
  
  // 获取token和用户数据
  const token = localStorage.getItem('token');
  const userDataStr = localStorage.getItem('data');
  
  // 如果没有token，重定向到登录页
  if (!token || !userDataStr) {
    next('/login');
    return;
  }
  
  try {
    // 解析用户数据
    const userData = JSON.parse(userDataStr);
    console.log("路由守卫中的用户数据:", JSON.stringify(userData));
    
    // 检查userData中的所有字段
    console.log("userData中的所有字段:");
    for (const key in userData) {
      console.log(`${key}: ${JSON.stringify(userData[key])}`);
    }
    
    // 使用department字段，如果不存在则为空字符串
    const userRole = userData.department || '员工';
    console.log("路由守卫检测到的用户角色 (department):", userRole);
    
    // 初始化store
    const store = useCounterStore();
    store.filterRoutesByRole(userRole);
    
    // 检查路由权限
    if (to.meta.roles && Array.isArray(to.meta.roles)) {
      // 员工特殊处理，确保可以访问流程审批
      if (userRole === '员工' && to.path.startsWith('/process')) {
        console.log("员工访问流程审批，允许通过");
        next();
        return;
      }
      
      // 行政部特殊处理，确保可以访问行政管理、员工管理、部门管理和流程审批
      if (userRole === '行政部') {
        if (to.path.startsWith('/administration') || 
            to.path.startsWith('/staff') || 
            to.path.startsWith('/organization') || 
            to.path.startsWith('/process')) {
          console.log("行政部访问特定路由，允许通过");
          next();
          return;
        }
      }
          // HR特殊处理，确保可以访问行政管理、员工管理、部门管理和流程审批
          if (userRole === 'HR') {
            if (to.path.startsWith('/administration') || 
                to.path.startsWith('/staff') || 
                to.path.startsWith('/organization') || 
                to.path.startsWith('/finance') || 
                to.path.startsWith('/process')) {
              console.log("行政部访问特定路由，允许通过");
              next();
              return;
            }
          }
      
      if (to.meta.roles.includes(userRole)) {
        next();
      } else {
        // 如果没有权限，重定向到工作台
        console.warn(`用户 ${userRole} 无权访问 ${to.path}`);
        next('/work');
      }
    } else {
      // 没有指定roles的路由，默认可访问
      next();
    }
  } catch (error) {
    console.error('解析用户数据出错:', error);
    next('/login');
  }
});

export default router
